// to avoid race condition and mix the sessions,
// never send two Ajax request one after another.
// The second Ajax request should be sent when
// the first call response is received
// see http://www.chipmunkninja.com/article/asyncsessions

// if a tag is in, the list is filtered by this tag
var tag_state;
tag_state = new Array;

// remember the timer for the tag selection
var timeo;

// notes window
var noteswin = "";

// keys that do not display the save button
var ignore_keys;
ignore_keys = new Array('9', '16', '17', '18', '27', '35', '36', '39', '37', '38', '40', '116');

Array.prototype.include = function(el) {
    for(var i=0; i<this.length;i++)
        if(this[i]==el) return i;
    return -1;
}

Array.prototype.remove = function(el) {
    for(var i=0; i<this.length;i++) {
        if(this[i]==el) this.splice(i,1);
    }
}

/*
String.prototype.sanitize = function() {
    for(var i=0; i<this.length;i++) {
        if(this[i]==' ') this[i]='_';
    }
}
*/

function create_notes(){
    noteswin = new Window('notes_dialog', {
        title: "Notes",
        top: 100,
        left: 250,
        zIndex: 150,
        resizable: true,
        showEffect: Element.show,
        hideEffect: Element.hide,
        width: 600,
        height: 400
    });
    noteswin.setCookie();
}

create_notes();

function notes(id){
    noteswin.getContent().innerHTML = "<iframe height=\"99%\" width=\"99%\" name=\"Notes_content\"  id=\"Notes_content\" SRC=\"/notes/show/" + id + "\"> </iframe>"
    noteswin.show();
}

// edit a task
function edit(id) {
    $('e' + id).src = '/images/loading.gif';
    new Ajax.Request('/task/edit/' + id, {
        asynchronous: true,
        evalScripts: true,
        onComplete: function(r){
            $('item_' + id).update(r.responseText);
        }
    });
}

function disp_del(id){
  if (id == '-1') {alert('Error: Task not found');return;}
  if (id == '-2') {alert('Error: Task can not be deleted');return;}
  new Effect.Fade($('de' + id));
  notice('Task has been deleted');
  new Effect.BlindUp($('item_' + id), {delay: 1});
  }

function del(id){
    if (confirm('Delete this task ?\n\"' + $('t' + id).value + '\"')) {
        var el = $('de' + id);
        el.src = '/images/loading.gif';
        new Ajax.Request('/task/delete/' + id, {
            asynchronous: true,
            evalScripts: true,
            onComplete: function(request){
                disp_del(request.responseText);
            }
        });
    }
    return false;
}

// update the task's deadline div
function update_task_deadline(task_id, deadline){
    var el = $('deadline' + task_id);
    el.innerHTML = deadline;
}

// update the task's tags div
function update_task_tags(task_id, tags){
    var el = $('tag' + task_id);
    el.innerHTML = tags;
}

// display all project tags
function display_tags(str) {
    $('tags').update(str);
    update_all_tag_display();
}

// update the display by filtering by tags
function filter_tasks(controller,project_id,tags) {
  $('loading').src = '/images/loading.gif';
  new Ajax.Request('/'+controller+'/filter_by_tag/' + project_id + '?t=' + tags, {
      asynchronous: true,
      evalScripts: true,
      onComplete: function(request){
        display_tasks(request.responseText);
      }});
}

function update_tag_display(tag) {
  var el = $('tag_filter_' + tag);
  if(tag_state.include(tag)==-1)
      el.className = 'tag';
  else
      el.className = 'tag on';
}

function toggle_tag_state(tag) {
  if(tag_state.include(tag)==-1)
      tag_state.push(tag);
  else
      tag_state.remove(tag);
}

// update tag_state's tag display
function update_all_tag_display() {
  tag_state._each(update_tag_display)
}

// filter by tag
function toggle_tag(controller,project_id, tag) {
    // change style
    clearTimeout(timeo);
    var el = $('loading')
    el.src = '/images/icon_clock.gif';
    el.show();
    toggle_tag_state(tag);
    update_tag_display(tag);
    timeo = setTimeout("filter_tasks('"+controller+"',"+project_id+", '"+tag_state.join(',')+"')",1000);
}

// done     : is the task done ?
// done_diff: did the done status changed ?
function saved(id, txt, done, done_diff) {
    //var el = $('s' + id);
    //new Effect.Fade(el);
    var el = $('item_' + id);
    el.update(txt);
    var to;
    if (done) {
        to = $('taskdoneul');
        if(done_diff) {
          //$('done_on_'+id).content("done just now");
          // if we done the last task tagged and if this tag was in the tag state,
          // then it will never be removed from the tag state
          // so we clear it now
          // TODO: check if this task was the last task with this tag
          tag_state.clear();
          }
        }
    else  {
        to = $('taskslist');
        //if(done_diff) $('done_on_'+id).content("undone");
        }
    if (el.parentNode != to) 
        to.insertBefore(el, to.firstChild);
    mover('');
    new Effect.Highlight(el);
    return false;
}

function save(id, createproject){
    if ($('p' + id).value == '') {
        alert('You must assign this task to a project. Type the name of the project this task belongs to in the first field. If the project does not exists, it will be created.');
        return false;
    }
    if (String(createproject) == "undefined") 
        createproject = 0;
    var el = $('s' + id);
    el.src = '/images/loading.gif';
    new Ajax.Request('/task/save/' + id, {
        asynchronous: true,
        evalScripts: true,
        onComplete: function(r){
            eval(r.responseText)
            //$('item_' + id).update(r.responseText);
        },
        parameters: Form.serialize('item_' + id) + "&C=" + createproject
    });
    return false;
}

function setclass(c, i){
    $('p' + i).className = c;
    $('t' + i).className = c;
    $('r' + i).className = c;
    $('pr' + i).className = c;
    $('da' + i).className = c;
}


function change(i, event){
    event = event || window.event;
    if (event != null) {
        event.preventDefault();
        var key = event.keyCode;
        //alert(key);
        if (ignore_keys.include(key)!=-1) 
            return true;
        //if(key == '13')
        //  save(i,0);
        if (event.ctrlKey && (key == '67')) 
            return true; // Ctr-C
        if (event.ctrlKey && (key == '65')) 
            return true; // Ctr-A
        if (event.ctrlKey && (key == '83')) {
            save(i);
            return false;
        } // Ctr-S, does not work...
    }
    // change style if done
    el = $('d' + i);
    if (el.checked) 
        setclass('done', i);
    else 
        setclass('', i);
    return false;
}

function recreate_sortable(el){
    Sortable.destroy(el);
    Sortable.create(el, {
        onUpdate: function(){
            new Ajax.Request('/task/order', {
                asynchronous: true,
                evalScripts: true,
                parameters: Sortable.serialize("taskslist")
            })
        }
    });
}

function displaynew(id, str){
    Element.hide('loading');
    new Insertion.Top('taskslist', str);
    recreate_sortable('taskslist');
    $('t' + id).focus();
    return false;
}

function add_new_row(){
    Element.show('loading');
    new Ajax.Request('/task/createnew', {
        asynchronous: true,
        evalScripts: true,
        onComplete: function(request){
            eval(request.responseText);
        }
    });
    return false;
}

function display_tasks(str){
    $('taskcontent').update(str);
    $('loading').hide();
    if(tag_state.length > 0) // not sortable if the list is filtered by a tag
      Sortable.destroy('taskslist'); // it does not work !
}

/*
function ajax_show_project_resp(str) {
  new Ajax.Request('/task/show_project_resp/' + str, {
      asynchronous: true,
      evalScripts: true,
      onComplete: function(request){
          $('members').update(request.responseText);
      }
  });
}
*/

function ajax_select_project(str) {
  new Ajax.Request('/task/select_project/' + str, {
      asynchronous: true,
      evalScripts: true,
      onComplete: function(request){
          eval(request.responseText);
      }
  });
}

function select_project(str){
    if (str == "") return;
    $('loading').show();
    tag_state.clear();
    ajax_select_project(str);      
    return false;
}

function select_resp(str){
    if (str == "") return;
    $('loading').show();
    new Ajax.Request('/task/select_resp/' + str, {
        asynchronous: true,
        evalScripts: true,
        onComplete: function(r){
            display_tasks(r.responseText)
        }
    });
    return false;
}

//Mouse over task's element
function mover(e, add){
    if (String(add) == "undefined") 
        add = "";
    if (add != "") 
        add = "<br/><br/><span>" + add + "</span>";
    switch (e) {
        case '':
        $('info').innerHTML = "" + add;
        break;
        case 'd':
        $('info').update("Click to indicate that this task is done" + add);
        break;
        case 'p':
        $('info').innerHTML = "Name of the project this task belongs to" + add;
        break;
        case 't':
        $('info').innerHTML = "Title of the task to do" + add;
        break;
        case 'r':
        $('info').innerHTML = "Responsible of this task" + add;
        break;
        case 'pr':
        $('info').innerHTML = "Priority of this task (number)" + add;
        break;
        case 's':
        $('info').innerHTML = "Save changes" + add;
        break;
        case 'de':
        $('info').innerHTML = "Delete permanently this task" + add;
        break;
        case 'a':
        $('info').innerHTML = "Add a new task" + add;
        break;
        case 'n':
        $('info').innerHTML = "Edit notes";
        break;
        case 'da':
        $('info').innerHTML = "Task\'s due date";
        break;
        default:
        $('info').innerHTML = "no help for " + e;
        break;
    }
}

function create_project_confirm(taskid){
    saveimg = $('s' + taskid);
    saveimg.src = '/images/save.png';
    var str = "This project does not exist.\nDo you want to create the project named '" + $('p' + taskid).value + "' ?";
    if (confirm(str)) 
        save(taskid, 1);
}

var calid;
function dispcal2(cal){
    change(calid, null);
}

function dispcal(id, value){
    calid = id;
    Calendar.setup({
        inputField: "da" + id,
        ifFormat: "%Y-%m-%d",
        showsTime: false,
        onUpdate: dispcal2
    });
}

function star_it(id) {
  new Ajax.Request('/task/star_it/' + id, {
      asynchronous: true,
      evalScripts: true,
      onComplete: function(r){
        eval(r.responseText)
      }
    });
}

function star(taskid, value){
    img = $('st' + taskid);
    switch (value) {
        case 1:
        str = 'on';
        break;
        default:
        str = 'off';
        break;
    }
    img.src = '/images/star_' + str + '_2.gif';
}
function sort_by_priority() {
  new Ajax.Request('/task/sort_by_priority/?t=' + tag_state.join(','), {
      asynchronous: true,
      evalScripts: true,
      onLoading: $('loading').show(),
      onComplete: function(r){
        $('taskcontent').update(r.responseText);
      }
    });

}
